import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class SaxParserUser extends DefaultHandler {

	private List<User> userList;
	   private String tmpValue;
	   private User tmpUser;

	public List<User> parseFileAndGetListOfUsers(String xmlFile) {

		SAXParserFactory spfFactory = SAXParserFactory.newInstance();
		try {
			SAXParser sParser = spfFactory.newSAXParser();
			sParser.parse(new File(xmlFile), this);
		} catch (ParserConfigurationException e) {
			Logger.log(MsgType.ERROR, "ParserConfiguration Exception");
		} catch (SAXException e) {
			Logger.log(MsgType.ERROR, "Not Well-formed XML Exception");
		} catch (IOException e) {
			Logger.log(MsgType.ERROR, "IO Error During xml file read");
		}

		return userList;
	}

	@Override
	public void startElement(String uri, String localName, String elName,
			Attributes attributes) throws SAXException {
		super.startElement(uri, localName, elName, attributes);
		if(elName.equalsIgnoreCase("users")){
			userList= new ArrayList<User>();
		}
		if(elName.equalsIgnoreCase("user")){
			tmpUser=new User();
		}
	}
	@Override
	public void endElement(String uri, String localName, String element)
			throws SAXException {
		super.endElement(uri, localName, element);
		if(element.equalsIgnoreCase("id")){
			tmpUser.setUserId(tmpValue);
		}
		if(element.equalsIgnoreCase("username")){
			tmpUser.setUserName(tmpValue);
		}
		if(element.equalsIgnoreCase("user")){
			userList.add(tmpUser);
		}
	}
	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		super.characters(ch, start, length);
		tmpValue= new String(ch, start, length);
	}
}
